var crypto = require('crypto');
var moment = require('moment');
var utils = require('../util/utils');
var WXPayData = require('../lib/WXPayData');
var WXApi = require('../lib/WXApi');
var config = require('../config/WXConfig');
var debug = require('debug')('WXService');

//创建订单号
function unifiedOrder(params, req, callback) {
    var orderParams = new WXPayData();
    //设置request传入的参数
    for (var param  in params) {
        orderParams.setParam(param, params[param]);
    }
    orderParams.initParam(params['trade_type']);
    orderParams.setParam("spbill_create_ip", utils.getClientIp(req));
    //TODO 本地测试IP
    debug('spbill_ip :'+utils.getClientIp(req));
    orderParams.setParam("spbill_create_ip", '10.11.21.33');
    var result = orderParams.checkParams();
    var sign = orderParams.makeSign();
    orderParams.setParam('sign', sign);
    WXApi.unifiedOrder(orderParams.paramsToXml(), function (data, err) {
        if (data) {
            if (data.xml.return_code === 'SUCCESS') {
                if (data.xml.result_code === 'SUCCESS') {
                    debug('unifiedOrder : '+JSON.stringify(data.xml));
                    callback(data.xml, null);
                }
                else {
                    result.code = -1;
                    result.message = data.xml.err_code_des;
                    callback(null, result);
                    return;
                }
            }
            else {
                result.code = -1;
                result.message = data.xml.return_msg;
                callback(null, result);
                return;
            }
        }
        else {
            result.code = -1;
            result.message = err;
            callback(null, result);
        }

    });
};
/*
 {
    out_trade_no:'xxx'
 }
 或
 {
    transaction_id:'xxx'
 }
*
* */
function queryOrder(orderParam, callback) {

    var paramData = new WXPayData();
    var nonceStr = getNonceStr();
    paramData.setParam("appid", config.APP_ID);
    paramData.setParam("mch_id", config.MCH_ID);
    //商户订单号和微信订单号传入一个即可
    if (orderParam['out_trade_no']) {
        paramData.setParam("out_trade_no", orderParam['out_trade_no']);
    }
    else if (orderParam['transaction_id']) {
        paramData.setParam("transaction_id", orderParam['transaction_id']);
    }
    paramData.setParam("nonce_str", nonceStr);
    paramData.setParam("sign_type", "MD5");
    var sign = paramData.makeSign();
    paramData.setParam('sign', sign);

    WXApi.queryOrder(paramData.paramsToXml(), function (data, err) {
        var result = {};
        if (data) {
            if (data.xml.return_code === 'SUCCESS') {
                if (data.xml.result_code === 'SUCCESS') {
                    callback(data.xml, null);
                }
                else {
                    result.code = -1;
                    result.message = data.xml.err_code_des;
                    callback(null, result);
                    return;
                }
            }
            else {
                result.code = -1;
                result.message = data.xml.return_msg;
                callback(null, result);
                return;
            }
        }
        else {
            result.code = -1;
            result.message = err;
            callback(null, result);
        }
    });
}

function closeOrder(outTradeNO, callback) {
    var paramData = new WXPayData();
    var nonceStr = getNonceStr();
    paramData.setParam("appid", config.APP_ID);
    paramData.setParam("mch_id", config.MCH_ID);
    paramData.setParam("out_trade_no", outTradeNO);
    paramData.setParam("nonce_str", nonceStr);
    paramData.setParam("sign_type", "MD5");
    var sign = paramData.makeSign();
    paramData.setParam('sign', sign);

    WXApi.closeOrder(paramData.paramsToXml(), function (data, err) {
        var result = {};
        if (data) {
            if (data.xml.return_code === 'SUCCESS') {
                if (data.xml.result_code === 'SUCCESS') {
                    callback(data.xml, null);
                }
                else {
                    debug(data.xml);
                    result.code = -1;
                    result.message = data.xml.err_code_des;
                    callback(null, result);
                    return;
                }
            }
            else {
                result.code = -1;
                result.message = data.xml.return_msg;
                callback(null, result);
                return;
            }
        }
        else {
            result.code = -1;
            result.message = err;
            callback(null, result);
        }
    });
}


//32位随机字符串
function getNonceStr() {
    var timestamp = moment().format('YYYYMMDDHHmmssSSS');
    return timestamp + Math.random().toString(36).substr(2, 15);
};

exports.getNonceStr = getNonceStr;
exports.unifiedOrder = unifiedOrder;
exports.queryOrder = queryOrder;
exports.closeOrder = closeOrder;

